import { AfterViewChecked, Component, ElementRef, EventEmitter, Injector, Output, ViewChild } from '@angular/core';
import { AppConsts } from '@shared/AppConsts';
import { AppComponentBase } from '@shared/common/app-component-base';
import { SupplierInput , ProfileServiceProxy, DataItemModel, DataItemServiceProxy, DataItemInputDto } from '@shared/service-proxies/service-proxies';
import { ModalDirective } from 'ngx-bootstrap';
import { IOrganizationUnitsTreeComponentData, OrganizationUnitsTreeComponent } from '../../shared/organization-unit-tree.component';
import * as _ from 'lodash';
import { finalize } from 'rxjs/operators';

@Component({
  selector: 'DataItemCreate',
  templateUrl: './DataItemCreate.component.html',
  styleUrls: ['./DataItemCreate.component.css']
})
export class DataItemCreateComponent extends AppComponentBase{
  @ViewChild('createOrEditModal') modal: ModalDirective;
  @Output() modalSave: EventEmitter<any> = new EventEmitter<any>();
  active = false;
  saving = false;
  _Item: DataItemModel = new DataItemModel();
  constructor(injector: Injector,
    private _dataItemServiceProxy: DataItemServiceProxy,
    private _profileService: ProfileServiceProxy) {
      super(injector);
    }
    show(ItemId?: string): void {
      console.log(ItemId)
      if (!ItemId) {
          this.active = true;
      }

      this._dataItemServiceProxy.getDataItemForEdit(ItemId).subscribe(resultdata => {
          this._Item = resultdata;
          console.log(resultdata);
          if (ItemId) {
              this.active = true;
          }
          this.modal.show();
      });
      // this.active = true;
      // this.modal.show();
  }
  onShown(): void {

  }
  save(): void {
    let input = new DataItemInputDto();
    input.model = this._Item;
    this.saving = true;

    console.log(input);
    this._dataItemServiceProxy.createOrUpdateDataItem(input)
        .pipe(finalize(() => { this.saving = false; }))
        .subscribe(() => {
            this.notify.info(this.l('SavedSuccessfully'));
            this.close();
            this.modalSave.emit(null);
        });
  }

  close(): void {
    this.active = false;
    this.modal.hide();
  }
}

